#include "connectionhandler.h"

ConnectionHandler::ConnectionHandler(QObject *parent) :
    QObject(parent)
{
    qDebug()<<"CONNECTION_HANDLER_CONSTRUCTOR";
    connect(&httpSocket,SIGNAL(stateChanged(int)),this,SLOT(connectionState(int)));
    connect(&httpSocket,SIGNAL(readyRead(QHttpResponseHeader)),this,SLOT(readyReadSlot(QHttpResponseHeader)));
    connect(&httpSocket,SIGNAL(dataReadProgress(int,int)),this,SLOT(inProgress(int,int)));
}

void ConnectionHandler::setPath(const QString &path)
{
    strPath=path;
}

QString ConnectionHandler::getPath()const
{
    return strPath;
}

void ConnectionHandler::setUrl(const QString &host, const QString &path)
{
   // httpSocket.closeConnection();
    httpSocket.abort();
    setPath(path);
    socket.setSocketOption(QAbstractSocket::KeepAliveOption,1);
    httpSocket.setSocket(&socket);
    httpSocket.setHost(host);
    httpSocket.get(path);         //connect
    //qDebug()<<
    qDebug()<<httpSocket.errorString();
    qDebug()<<host<<path;
}


void ConnectionHandler::started()  //loading startet
{
    qDebug()<<"LOADING STARTED...";
}

void ConnectionHandler::inProgress(int done, int total)
{
    qDebug()<<done<<" : "<<total;
}

void ConnectionHandler::readyReadSlot(const QHttpResponseHeader &header)   //downloading finished
{
    page.mainFrame()->setHtml(httpSocket.readAll());
    //parse(true);                                        //TODO: function of Parser!
    emit finished(page);                                    //emit a finished signal when downloading finished
}

QHttp* ConnectionHandler::getQHttp()
{
    return &httpSocket;
}

/*QWebPage ConnectionHandler::getWebPage() const
{
    return page;
}*/

/*reconnect when connection lost*/
void ConnectionHandler::connectionState(int state)
{
    switch(state)
    {
    case 0:         //disconnected
        httpSocket.get(getPath());   //reconnect
    }
}
